//
//  Record.m
//  SimulacraDB
//
//  Created by Andre Cohen on 8/9/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Record.h"


@implementation Record

@synthesize wrapper;
@synthesize dataBlocks;

- (id)initWithWrapperClass:(Class)wrapperClass
				 dataClass:(Class)dataClass{
	return [self initWithWrapperClass:wrapperClass
						  dataClasses:[NSMutableArray arrayWithObject:dataClass]];
}

- (id)initWithWrapperClass:(Class)wrapperClass
			   dataClasses:(NSArray *)dataClasses{
	[super init];
	
	if(wrapperClass!=nil){
		wrapper = [[[wrapperClass alloc] init] autorelease];
	}
	if(dataClasses!=nil){
		dataBlocks = [[[NSMutableArray alloc] init] autorelease];
		int i;
		for(i=0;i<[dataClasses count];i++){
			id c = [[dataClasses objectAtIndex:i] alloc];
			[dataBlocks addObject:[[(id<RecordDataProtocol>)c initWithData:nil] autorelease]];
		}
	}
	
	return self;
}

- (ByteArray *)toByteArray {
	ByteArray *array = [[[ByteArray alloc] init] autorelease];
	int i;
	
	// Write wrapper
	[array appendByteArray:[wrapper toByteArray]];
	
	// Write number of data blocks -- CAN BE ASSUMED CONSTANT
	// [array appendInt:[dataBlocks count]];
	
	// Write each data block
	for(i=0;i<[dataBlocks count];i++){
		// Write data block size
		[array appendInt:[(NSObject <RecordDataProtocol> *)[dataBlocks objectAtIndex:i] size]];
		[array appendByteArray:[[dataBlocks objectAtIndex:i] toByteArray]];
	}
	return array;
}

- (NSString *)description {
	NSMutableString *desc = [[[NSMutableString alloc] init] autorelease];
	int i;
	
	if(wrapper)
		[desc appendFormat:@"%@: ",[wrapper description]];
	
	[desc appendFormat:@"%d:",[dataBlocks count]];
	
	for(i=0;i<[dataBlocks count];i++){
		NSObject <RecordDataProtocol> *r = [dataBlocks objectAtIndex:i];
		[desc appendFormat:@"[%d][%@]",[r size],[r description]];
	}
	
	if([desc length]>0)
		return desc;
	return @"NULL";
}

- (Record *)clone {
	NSMutableArray *dataClasses = [[[NSMutableArray alloc] init] autorelease];
	int i;
	for(i=0;i<[dataBlocks count];i++)
		[dataClasses addObject:[[dataBlocks objectAtIndex:i] class]];
	
	return [[[Record alloc] initWithWrapperClass:[wrapper class]
									 dataClasses:dataClasses] autorelease];
}

- (int)size {
	int i, size = [wrapper size];
	for(i=0;i<[dataBlocks count];i++)
		size = size + [(NSObject <RecordDataProtocol> *)[dataBlocks objectAtIndex:i] size] + 2;
	return size;
}

- (NSObject <RecordDataProtocol> *)getBlock:(int)block {
	return [dataBlocks objectAtIndex:block];
}

- (BOOL)recordBlock:(int)block equalTo:(id)object {
	return [[self getBlock:block] equalTo:[object getBlock:block]];
	// [[[self wrapper] rid] equalTo:[[(Record *)object wrapper] rid]];
}
- (BOOL)recordBlock:(int)block lessThan:(Record *)record {
	return [[self getBlock:block] lessThan:[record getBlock:block]];
}
- (BOOL)recordBlock:(int)block greaterThan:(Record *)record {
	return [[self getBlock:block] greaterThan:[record getBlock:block]];
}

@end
